<template>
  <div class="athlete_team">
    <div v-loading="checkEntryLoading" class="gameEntry_shadow check_shadow">
      <div class="top_control gl_clear">
        <el-button class="gl_fl" type="primary" size="mini" @click="clickTeamPlayer">选择参赛运动员</el-button>
        <el-button class="gl_fl" type="default" size="mini" @click="clickImportAthlete">批量导入人员</el-button>
        <el-button class="gl_fl" type="default" size="mini" @click="clickAddAthlete">增加运动员</el-button>
        <el-button class="gl_fr" type="warning" plain size="mini" :disabled="!players.length" @click="removeAllPlayer">清空运动员</el-button>
      </div>
      <div>
        <el-radio-group v-model="checkedMember" size="mini">
          <el-tag v-for="(item, index) in players" :key="index" class="gl_mr_10 gl_mb_10" closable :disable-transitions="true" effect="plain" @close="removePlayer(item, index)">
            <el-radio :label="item" class="member_check_width" @change="onChangeMemberRadio">
              <span>{{ item.name }} </span>
              <span v-if="item.genderCode" class="gl_mr_5">({{ dictGenderMap[item.genderCode].value }})</span>
              <i v-show="item._hasEntry" class="el-icon-star-on" />
            </el-radio>
          </el-tag>
        </el-radio-group>
        <div v-if="!players.length" class="tip_noData">请先选择参赛运动员，选中运动员获取报名项目</div>
      </div>
    </div>

    <!-- 报项列表 -->
    <div v-if="entryList.length" v-loading="entryListLoading" class="gameEntry_shadow entry_shadow">
      <!-- 联赛且为决赛时，需要显示赛区选择 -->
      <div v-if="gameInfo.isFinal && substationList.length" class="event_group">
        <div class="event_title">赛区选择</div>
        <div class="event_list">
          <el-radio-group v-model="activeSubstation">
            <el-radio
              v-for="(item, index) in substationList"
              :key="index"
              style="margin-left: 0px"
              class="event_item"
              :label="item.id"
              border
            >
              {{ item.competitionName }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <div v-for="(item, index) in entryShowList" :key="index" class="event_group">
        <div class="event_title">{{ item.name }}</div>
        <div class="event_list">
          <el-checkbox-group v-model="entryCheckGroupData[item.categoryId]" :max="item.maxEntry">
            <template v-for="(jtem, jndex) in item.children">
              <el-checkbox v-if="jtem.eventRegTypeCode === 'I'" :key="jndex" class="event_item" :label="jtem" border :disabled="Boolean(isCategory && isAOrB && jtem.categoryGroupTypeCode != 'C' && isAOrB != jtem.categoryGroupTypeCode)">
                <span>{{ jtem.eventGroupName }}{{ jtem.eventShortName }}</span>
                <!-- <el-select v-if="jtem.eventRegTypeCode !== 'I'" v-model="jtem.athleteEntriedTeamNo" style="width:74px" placeholder="分组" size="mini" @click.native.stop.prevent>
                  <el-option
                    v-for="(ktem, kndex) in jtem.$eventMaxTeamNo"
                    :key="kndex"
                    :label="ktem + '组'"
                    :value="ktem"
                  />
                </el-select> -->
              </el-checkbox>
              <div
                v-if="jtem.eventRegTypeCode !== 'I'"
                :key="jndex"
                class="mock_checkbox_wrap"
                :class="{
                  'checked': jtem.athleteHasEntried,
                  'disabled': ((item.hasEntry >= item.maxEntry) && !jtem.athleteHasEntried) || (isCategory && isAOrB && jtem.categoryGroupTypeCode && jtem.categoryGroupTypeCode != 'C' && isAOrB != jtem.categoryGroupTypeCode)
                }"
                @click="chooseTeamMember(jtem, (item.hasEntry >= item.maxEntry) && !jtem.athleteHasEntried)"
              >
                <span class="mock_checkbox gl_mr_10" />
                <span class="gl_mr_10">{{ jtem.eventGroupName }}{{ jtem.eventShortName }}</span>
                <i class="el-icon-user-solid gl_mr_10" title="成员选择" />
              </div>
            </template>
          </el-checkbox-group>
        </div>
      </div>
    </div>

    <!-- 步骤控制按钮 -->
    <el-row v-show="entryList.length" class="control_row">
      <el-col :span="24" align="center">
        <el-button type="primary" size="small" :loading="submitLoading" @click="clickSubmit()">提交报名</el-button>
      </el-col>
    </el-row>

    <TeamCompetition
      ref="refTeamCompetitionMember"
      :title="teamCompetitionTitle"
      :require-member="mainMember"
      :gameInfo = 'gameInfo'
      :team-entry="teamCompetitionTeamEntry"
      :option-member="teamCompetitionLeftList"
      :max-select-member-num="teamCompetitionMaxCount"
      :min-select-member-num="teamCompetitionMinCount"
      :select-member="teamCompetitionRightList"
      @onTeamCompetitionSubmit="onTeamCompetitionSubmit"
      @onDeleteGroupMember="onDeleteGroupMember('TeamCompetition')"
    />

    <TeamNoneCompetition
      ref="refTeamNoneCompetitionMember"
      :title="teamNoneCompetitionTitle"
      :require-member="mainMember"
      :gameInfo = 'gameInfo'
      :team-entry="teamNoneCompetitionTeamEntry"
      :option-member="teamNoneCompetitionLeftList"
      :max-select-member-num="teamNoneCompetitionMaxCount"
      :min-select-member-num="teamNoneCompetitionMinCount"
      :select-member="teamNoneCompetitionRightList"
      @onTeamNoneCompetitionSubmit="onTeamNoneCompetitionSubmit"
      @onDeleteGroupMember="onDeleteGroupMember('TeamNoneCompetition')"
    />
  </div>
</template>

<script>
import {
  api_POST_EventsManagementEntryQueryEventsToEntryForRegisters, // 1-获取已存在人员可报的赛事项目列表
  api_GET_EventsManagementEntryTeamEntry, // 获取团体报项
  api_GET_EventsManagementEntryTeamEntryMemberCandidates, // 获取团体报项候选人员列表
  api_POST_EventsManagementEntrySaveTeamEntry, // 保存团体报项
  api_DELETE_EventsManagementEntryTeamEntry, // 删除团体报项
  api_POST_EventsManagementEntryQuerySubCompetitionsToEntryForRegisters // 0-获取已存在人员联赛决赛代表的分站赛赛事列表
} from '@/extend/api/gameswaggerApi/app';

import {
  SiSTKWEventsManagementGetEntryEventsInput // 1-获取已存在人员可报的赛事项目列表
} from '@/lib/form/game/swaggerForm';

import TeamCompetition from '@/components/TeamCompetition';
import TeamNoneCompetition from '@/components/TeamNoneCompetition';

export default {
  components: {
    TeamCompetition,
    TeamNoneCompetition
  },
  props: {
    submitLoading: {
      type: Boolean,
      default: false
    },
    // 报名人员列表
    players: {
      type: Array,
      default () {
        return [];
      }
    },
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    dict: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    return {
      activeSubstation: '',
      substationList: [],
      // 选择报名的人
      checkedMember: {},
      entryVO: new SiSTKWEventsManagementGetEntryEventsInput(), // 1-获取已存在人员可报的赛事项目列表
      entryList: [],
      entryShowList: [],
      isCategory: false,
      isAOrB: '',
      entryCheckGroupData: {},
      checkEntryLoading: false,
      entryListLoading: false,

      mainMember: {},

      teamCompetitionTitle: '',
      teamCompetitionLeftList: [],
      teamCompetitionRightList: [],
      teamCompetitionMaxCount: 0,
      teamCompetitionMinCount: 0,
      teamCompetitionCurrent: {}, // 当前选中的团体竞技项目
      teamCompetitionTeamEntry: {}, // 获取到的团体报项数据

      teamNoneCompetitionTitle: '',
      teamNoneCompetitionLeftList: [],
      teamNoneCompetitionRightList: [],
      teamNoneCompetitionMaxCount: 0,
      teamNoneCompetitionMinCount: 0,
      teamNoneCompetitionCurrent: {}, // 当前选中的普通团体项目
      teamNoneCompetitionTeamEntry: {} // 获取到的团体报项数据
    };
  },
  computed: {
    dictGenderMap() {
      const _map = {};
      this.dict.gender.forEach(item => {
        _map[item.code] = item;
      });
      return _map;
    }
  },
  watch: {
    userInfo: {
      deep: true,
      handler() {
        this.resetViewData();
      }
    },
    entryCheckGroupData: {
      deep: true,
      handler(newVal) {
        let ab = '';
        for (const k in newVal) {
          const ktem = newVal[k];
          if (ktem.length > 0 && ktem[0].categoryGroupTypeCode !== 'C' && ktem[0].categoryGroupTypeCode !== null) {
            ab = ktem[0].categoryGroupTypeCode || '';
          }
        }
        const code = this.gameInfo.setting && this.gameInfo.setting.chargeTypeCode;
        this.isCategory = code === 'Category';
        this.isAOrB = ab;
        console.log(newVal, this.isAOrB);
      }
    },
    checkedMember: {
      handler(newVal, val) {
        if (newVal.id !== val.id) {
          this.entryList = [];
          this.entryCheckGroupData = {};
          this.mainMember = newVal;
        }
      }
    }
  },
  methods: {
    // 团体非竞技成员选择
    entryTeamNoneCompetitionMember(data) {
      this.teamNoneCompetitionCurrent = data;
      this.entryListLoading = true;
      this.teamNoneCompetitionTitle = data.eventLongName;
      this.teamNoneCompetitionMaxCount = data.maxTeamMembersCount;
      this.teamNoneCompetitionMinCount = data.minTeamMembersCount;

      const _promiseEntry = this.getTeamEntry({
        EventId: data.id,
        RegisterId: this.checkedMember.id,
        DelegationId: this.requiredIdData.delegationId
      });

      const _promiseEntryMember = this.getTeamEntryMemberCandidates({
        EventId: data.id,
        DelegationId: this.requiredIdData.delegationId
      });

      Promise.all([_promiseEntry, _promiseEntryMember])
        .then(
          res => {
            this.entryListLoading = false;
            const teamEntryRes = res[0];
            const teamEntryMemberCandidatesRes = res[1];
            this.teamNoneCompetitionTeamEntry = teamEntryRes;
            this.teamNoneCompetitionTitle = `${this.teamNoneCompetitionTitle} ${teamEntryRes.teamNo}组`;
            this.teamNoneCompetitionLeftList = teamEntryMemberCandidatesRes;
            this.teamNoneCompetitionRightList = teamEntryRes.members;
            this.$refs.refTeamNoneCompetitionMember.open();
          }
        )
        .catch(
          error => {
            this.entryListLoading = false;
            console.log('error: ', error);
          }
        );
    },
    // 团体竞技成员选择
    entryTeamCompetitionMember(data) {
      this.teamCompetitionCurrent = data;
      this.entryListLoading = true;
      this.teamCompetitionTitle = data.eventLongName;
      this.teamCompetitionMaxCount = data.maxTeamMembersCount;
      this.teamCompetitionMinCount = data.minTeamMembersCount;

      const _promiseEntry = this.getTeamEntry({
        EventId: data.id,
        RegisterId: this.checkedMember.id,
        DelegationId: this.requiredIdData.delegationId
      });

      const _promiseEntryMember = this.getTeamEntryMemberCandidates({
        EventId: data.id,
        DelegationId: this.requiredIdData.delegationId
      });

      Promise.all([_promiseEntry, _promiseEntryMember])
        .then(
          res => {
            this.entryListLoading = false;
            const teamEntryRes = res[0];
            const teamEntryMemberCandidatesRes = res[1];
            this.teamCompetitionTeamEntry = teamEntryRes;
            this.teamCompetitionTitle = `${this.teamCompetitionTitle} ${teamEntryRes.teamNo}组`;
            this.teamCompetitionLeftList = teamEntryMemberCandidatesRes;
            this.teamCompetitionRightList = this.formatWeightClasses(data, teamEntryRes.members);
            this.$refs.refTeamCompetitionMember.open();
          }
        )
        .catch(
          error => {
            this.entryListLoading = false;
            console.log('error: ', error);
          }
        );
    },
    formatWeightClasses (data, members) {
      members = members || [];
      const _rightList = JSON.parse(JSON.stringify(data.weightClasses));

      for (let i = 0; i < _rightList.length; i++) {
        const item = _rightList[i];
        item._children = members.filter(jtem => jtem.eventWeightClassId === item.id);
      }
      console.log('data, members: ', data, members);
      return _rightList;
    },
    onDeleteGroupMember (type) {
      // 团体竞技
      if (type === 'TeamCompetition') {
        this.deleteGroupMemberApi({
          EntryId: this.teamCompetitionTeamEntry.teamEntryId,
          DelegationId: this.requiredIdData.delegationId,
          EventId: this.teamCompetitionCurrent.id
        }, 'refTeamCompetitionMember');
      }
      // 团体
      if (type === 'TeamNoneCompetition') {
        this.deleteGroupMemberApi({
          EntryId: this.teamNoneCompetitionTeamEntry.teamEntryId,
          DelegationId: this.requiredIdData.delegationId,
          EventId: this.teamNoneCompetitionCurrent.id
        }, 'refTeamNoneCompetitionMember');
      }
    },
    // 删除整组成员
    deleteGroupMemberApi (vo, refName) {
      api_DELETE_EventsManagementEntryTeamEntry(vo)
        .then(
          res => {
            this.$emit('onReGetByPerson'); // 重新请求byperson接口

            // 当提交团体竞技或混合团体竞技后
            if (refName === 'refTeamCompetitionMember') {
              this.teamCompetitionCurrent.athleteHasEntried = false;
              const _categoryId = this.teamCompetitionCurrent.$categoryId;

              // 如果 entryCheckGroupData 中没有则要push,有则不需要
              const _findCurrIndex = this.entryCheckGroupData[_categoryId].findIndex(item => item.id === this.teamCompetitionCurrent.id);
              if (_findCurrIndex !== -1) {
                this.changeEntryShowListHasEntry(_categoryId, 'sub');
                this.entryCheckGroupData[_categoryId].splice(_findCurrIndex, 1);
              }
            }

            // 当提交普通团体后
            if (refName === 'refTeamNoneCompetitionMember') {
              this.teamNoneCompetitionCurrent.athleteHasEntried = false;
              const _categoryId = this.teamNoneCompetitionCurrent.$categoryId;

              // 如果 entryCheckGroupData 中没有则要push,有则不需要
              const _findCurrIndex = this.entryCheckGroupData[_categoryId].findIndex(item => item.id === this.teamNoneCompetitionCurrent.id);
              if (_findCurrIndex !== -1) {
                this.changeEntryShowListHasEntry(_categoryId, 'sub');
                this.entryCheckGroupData[_categoryId].splice(_findCurrIndex, 1);
              }
            }
            // this.checkEntry(); // 重新检测报项信息

            this.$refs[refName].close(); // 关闭弹窗
            this.$message({
              message: `删除团体报项成功`,
              type: 'success',
              showClose: true
            });
          }
        )
        .catch(
          error => {
            this.$refs[refName].hideLoading();
            this.$message({
              message: `删除团体报项失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 选择团体成员 非重竞技
    chooseTeamMember (data, isDisabled) {
      if (!isDisabled) {
        if (data.preEventTypeCode === 'CompetitiveTeam' || data.preEventTypeCode === 'MixedCompetitiveTeam') {
          this.entryTeamCompetitionMember(data);
        } else {
          this.entryTeamNoneCompetitionMember(data);
        }
      } else {
        console.log('chooseTeamMember', isDisabled);
      }
    },
    // 获取团体报项候选人员列表
    getTeamEntryMemberCandidates (qo) {
      return new Promise((reslove, reject) => {
        api_GET_EventsManagementEntryTeamEntryMemberCandidates(qo)
          .then(
            res => {
              reslove(res);
            }
          )
          .catch(
            error => {
              this.$message({
                message: `获取团体报项候选人员列表失败 ${error.error.message}`,
                type: 'error',
                showClose: true
              });
              reject(error);
            }
          );
      });
    },
    // 获取团体报项API
    getTeamEntry(qo) {
      return new Promise((reslove, reject) => {
        api_GET_EventsManagementEntryTeamEntry(qo)
          .then(
            res => {
              reslove(res);
            }
          )
          .catch(
            error => {
              reject(error);
              this.$message({
                message: `获取团体报项失败 ${error.error.message}`,
                type: 'error',
                showClose: true
              });
            }
          );
      });
    },
    // 团体竞技报名
    onTeamCompetitionSubmit (data) {
      const _ids = data.map(item => {
        return {
          registerIds: item._children.map(jtem => jtem.registerId || jtem.id)
        };
      });

      this.submitTeamEntry({
        eventId: this.teamCompetitionCurrent.id,
        delegationId: this.requiredIdData.delegationId,
        entryId: this.teamCompetitionTeamEntry.teamEntryId || '',
        teamNo: this.teamCompetitionTeamEntry.teamNo,
        weightClasses: _ids
      }, 'TeamCompetition');
    },
    // 团体非竞技确认报名
    onTeamNoneCompetitionSubmit (data) {
      const _ids = data.map(item => item.registerId || item.id);

      this.submitTeamEntry({
        eventId: this.teamNoneCompetitionCurrent.id,
        delegationId: this.requiredIdData.delegationId,
        entryId: this.teamNoneCompetitionTeamEntry.teamEntryId || '',
        teamNo: this.teamNoneCompetitionTeamEntry.teamNo,
        weightClasses: [{ registerIds: _ids }]
      }, 'TeamNoneCompetition');
    },
    // 获取已存在人员联赛决赛代表的分站赛赛事列表
    getSubstationList (vo) {
      api_POST_EventsManagementEntryQuerySubCompetitionsToEntryForRegisters(vo)
        .then(
          res => {
            this.substationList = res || [];
            const _findResult = res.find(item => item.hasUsed);
            this.activeSubstation = _findResult ? _findResult.id : '';
          }
        )
        .catch(
          error => {
            this.$message({
              message: `获取分站列表失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 保存团体报项API
    submitTeamEntry(vo, type) {
      api_POST_EventsManagementEntrySaveTeamEntry(vo)
        .then(
          res => {
            // this.checkEntry(() => {
            //   // 静默提交一次报名,此方式已废弃
            //   this.clickSubmit(true);
            // });

            // 不重新获取byperson，目的是让用户以为报名还未完成，诱导点击提交报名按钮，触发提交教练领队信息
            // this.$emit('onReGetByPerson'); // 重新获取byperson

            // 当提交团体竞技或混合团体竞技后
            if (type === 'TeamCompetition') {
              this.teamCompetitionCurrent.athleteHasEntried = true;
              const categoryId = this.teamCompetitionCurrent.eventCategoryId;
              if (this.entryCheckGroupData[categoryId]) {
                this.changeEntryShowListHasEntry(categoryId, 'add');
                this.teamCompetitionCurrent.athleteEntriedTeamNo = res.teamNo;
                // 如果 entryCheckGroupData 中没有则要push,有则不需要
                const _findCurr = this.entryCheckGroupData[categoryId].find(item => item.id === this.teamCompetitionCurrent.id);
                if (!_findCurr) {
                  this.entryCheckGroupData[categoryId].push(this.teamCompetitionCurrent);
                }
              }
              this.$refs.refTeamCompetitionMember.close();
            }

            // 当提交普通团体后
            if (type === 'TeamNoneCompetition') {
              this.teamNoneCompetitionCurrent.athleteHasEntried = true;
              const categoryId = this.teamNoneCompetitionCurrent.eventCategoryId;
              if (this.entryCheckGroupData[categoryId]) {
                this.changeEntryShowListHasEntry(categoryId, 'add');
                this.teamNoneCompetitionCurrent.athleteEntriedTeamNo = res.teamNo;
                // 如果 entryCheckGroupData 中没有则要push,有则不需要
                const _findCurr = this.entryCheckGroupData[categoryId].find(item => item.id === this.teamNoneCompetitionCurrent.id);
                if (!_findCurr) {
                  this.entryCheckGroupData[categoryId].push(this.teamNoneCompetitionCurrent);
                }
              }
              this.$refs.refTeamNoneCompetitionMember.close();
            }

            // 不给用户成功提示，目的是让用户以为报名还未完成，诱导点击提交报名按钮，触发提交教练领队信息
            // this.$message({
            //   message: `保存团体报项成功`,
            //   type: 'success',
            //   showClose: true
            // });
          }
        )
        .catch(
          error => {
            if (type === 'TeamCompetition') {
              this.$refs.refTeamCompetitionMember.hideLoading();
            }
            if (type === 'TeamNoneCompetition') {
              this.$refs.refTeamNoneCompetitionMember.hideLoading();
            }
            this.$message({
              message: `保存团体报项失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    changeEntryShowListHasEntry (categoryId, type) {
      const _findIndex = this.entryShowList.findIndex(item => item.categoryId === categoryId);
      if (_findIndex !== -1) {
        let _num = this.entryShowList[_findIndex].hasEntry;
        if (type === 'add') {
          _num++;
        }
        if (type === 'sub') {
          _num--;
        }
        this.$set(this.entryShowList[_findIndex], 'hasEntry', _num);
      }
    },
    // ===
    // 点击 选择参赛运动员
    clickTeamPlayer () {
      this.$emit('clickTeamPlayer');
    },
    // 点击 增加运动员
    clickAddAthlete () {
      this.$emit('clickAddAthlete');
    },
    // 点击 批量导入人员
    clickImportAthlete () {
      this.$emit('clickImportAthlete');
    },
    // 点击执行上一步操作
    clickPrevStep () {
      this.$emit('onPrevStep');
    },
    // 点击提交报名
    clickSubmit (isSilent) {
      console.log('isSilent: ', isSilent);
      // 校验运动员是否选择
      if (!this.checkedMember.id) {
        this.$message({
          message: `请选择参赛运动员`,
          type: 'warning',
          showClose: true
        });
        return;
      }

      // 校验是否选择报项
      let _entryCheckList = [];
      for (const k in this.entryCheckGroupData) {
        const ktem = this.entryCheckGroupData[k];
        _entryCheckList = _entryCheckList.concat(ktem);
      }
      if (!_entryCheckList.length) {
        this.$message({
          message: `请选择要报名的项目`,
          type: 'warning',
          showClose: true
        });
        return;
      }

      // 处理报项数据，准备报名
      const _allEventList = [];

      for (let i = 0; i < _entryCheckList.length; i++) {
        const item = _entryCheckList[i];
        if (item.eventRegTypeCode === 'I') {
          // 个人项目
          _allEventList.push({
            eventId: item.id
          });
        } else {
          // 团体项目，判断是否选择了分组
          if (item.athleteEntriedTeamNo) {
            _allEventList.push({
              eventId: item.id,
              teamNo: item.athleteEntriedTeamNo,
              teamName: item.athleteEntriedTeamNo + '组'
            });
          } else {
            this.$message({
              message: `${item.eventLongName} 未选择分组`,
              type: 'warning',
              showClose: true
            });
            return false;
          }
        }
      }

      const _eventData = {
        entrySubstationId: this.activeSubstation,
        _allEventList: _allEventList
      };

      this.$emit('onSubmitTeamEntry', this.checkedMember.id, _eventData, isSilent);
    },
    // 重置页面为初始值显示
    resetViewData() {
      this.checkedMember = {};
      // this.entryList = [];
      // this.entryShowList = [];
    },
    // 移除运动员
    removePlayer (item, index) {
      if (item === this.checkedMember) {
        this.checkedMember = {};
        this.entryList = [];
        this.entryCheckGroupData = {};
      }
      this.players.splice(index, 1);
    },
    // 点击清空运动员
    removeAllPlayer () {
      this.checkedMember = {};
      this.players.length = 0;
      // 清除报项列表及生成的复选存储
      this.entryList = [];
      this.entryCheckGroupData = {};
    },
    // 当选择运动员单选按钮时，获取报项，如果是联赛中的决赛则需要获取赛区列表
    onChangeMemberRadio () {
      if (this.gameInfo.isFinal) {
        this.getSubstationList({
          competitionId: this.gameInfo.id,
          registerId: this.checkedMember.id,
          delegationId: this.requiredIdData.delegationId,
          hasEntriedEvent: true
        });
      }
      this.checkEntry();
    },
    // 检测报项信息
    checkEntry (callback) {
      if (!this.checkedMember.id) {
        this.$message({
          message: `请选择一名参赛运动员`,
          type: 'warning',
          showClose: true
        });
        return;
      }
      this.entryVO.competitionId = this.gameInfo.id;
      this.entryVO.registerId = this.checkedMember.id;
      this.entryVO.delegationId = this.requiredIdData.delegationId;
      this.entryVO.hasEntriedEvent = true;
      this.checkEntryLoading = true;
      api_POST_EventsManagementEntryQueryEventsToEntryForRegisters(this.entryVO)
        .then(
          res => {
            if (res.length) {
              this.entryList = res;
              this.entryCheckGroupData = {};
              this.entryShowList = this.formatEntryShowData(res);
              // this.$message({
              //   message: `检测成功`,
              //   type: 'success',
              //   showClose: true
              // });
              if (callback && typeof callback === 'function') {
                callback();
              }
            } else {
              this.$message({
                message: `没有检测到可以报名的项目`,
                type: 'warning',
                showClose: true
              });
            }
            this.checkEntryLoading = false;
          }
        )
        .catch(
          error => {
            this.$message({
              message: `获取人员可报的赛事项目列表失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
            this.checkEntryLoading = false;
          }
        );
    },
    // 处理报项显示数据
    formatEntryShowData (list) {
      const _returnData = {};
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        item.$categoryId = item.eventCategoryId;
        item.$eventMaxTeamNo = item.eventMaxTeamNo ? item.eventMaxTeamNo : 20;
        if (_returnData[item.$categoryId]) {
          _returnData[item.$categoryId].children.push(item);
        } else {
          _returnData[item.$categoryId] = {
            categoryId: item.$categoryId,
            categoryCreateTime: item.eventCategoryCreationTime,
            name: item.eventCategoryName,
            maxEntry: item.categoryMaxEntry,
            children: [item]
          };
          // 处理复选框数据
          this.formatEntryShowDataCheckbox(item.$categoryId);
        }
        // 报了这个项目
        if (item.athleteHasEntried) {
          this.entryCheckGroupData[item.$categoryId].push(item);
        }
      }

      for (const k in _returnData) {
        const ktem = _returnData[k];
        let hasEntry = 0;
        ktem.children.forEach(item => {
          if (item.athleteHasEntried) {
            hasEntry++;
          }
        });
        ktem.hasEntry = hasEntry;
        ktem.children.sort((a, b) => {
          const _a = a.eventCreationTime;
          const _b = b.eventCreationTime;
          if (_a < _b) { return -1; }
          if (_a > _b) { return 1; }
          return 0;
        });
      }

      const _returnList = Object.values(_returnData);
      _returnList.sort((a, b) => {
        const _a = a.categoryCreateTime;
        const _b = b.categoryCreateTime;
        if (_a < _b) { return -1; }
        if (_a > _b) { return 1; }
        return 0;
      });
      return _returnList;
    },
    // 处理报项显示数据的复选框
    formatEntryShowDataCheckbox (categoryId) {
      if (categoryId in this.entryCheckGroupData) {
        return;
      }
      this.$set(this.entryCheckGroupData, categoryId, []);
    },
    // 外部调用
    onRemovedAthleteForCheckEntry (id) {
      if (id === this.checkedMember.id) {
        this.onChangeMemberRadio();
      }
    },
    matchAthleteEntryFromByPerson (list) {
      const entryAthlete = {};
      list.forEach(item => {
        entryAthlete[item.sourceRegister.id] = item.sourceRegister.name;
      });
      this.players.forEach((item, index) => {
        if (item.id in entryAthlete) {
          this.$set(this.players[index], '_hasEntry', true);
        } else {
          this.$set(this.players[index], '_hasEntry', false);
        }
      });
    },
    // 外部调用
    chooseAthleteAndGetEntry (athlete) {
      // 供外部调用
      const _findPlayer = this.players.find(item => item.id === athlete.id);
      if (_findPlayer) {
        this.checkedMember = _findPlayer;
      } else {
        athlete._hasEntry = true;
        this.players.push(athlete);
        this.checkedMember = athlete;
      }
      document.body.scrollTop = document.documentElement.scrollTop = 600;
      this.onChangeMemberRadio();
    }
  }
};
</script>

<style>
.athlete_team .el-checkbox.is-bordered {
  height: auto;
  min-height: 40px;
}
</style>

<style lang="scss" scoped>
.check_shadow {
  padding: 20px 30px;
  margin-bottom: 10px;
}
.entry_shadow {
  padding: 20px 30px;
  background-color: #fff;
}
.top_control {
  padding-bottom: 9px;
  border-bottom: 1px solid #d9d9d9;
  margin-bottom: 14px;
}

.member_check_width {
  min-width: 100px;
  margin-right: 10px;
}

.event_group {
  margin-bottom: 10px;
}
.control_row {
  margin-bottom: 30px;
}
.event_title {
  position: relative;
  height: 22px;
  line-height: 22px;
  font-size: 16px;
  font-weight: bold;
  color: #353434;
  margin-bottom: 8px;
}
.event_item {
  margin-bottom: 10px;
  margin-right: 10px;
}
.tip_noData {
  font-size: 13px;
  text-align: center;
  line-height: 60px;
  color: #c1c1c1
}
.individual_list_noData {
  padding: 140px 0px 215px;
  text-align: center;
  font-size: 16px;
  color: #c1c1c1;
}

.mock_checkbox_wrap {
  display: inline-block;
  vertical-align: top;
  min-height: 40px;
  padding: 9px 20px 9px 10px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  line-height: 20px;
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}
.mock_checkbox_wrap span {
  vertical-align: middle;
}
.mock_checkbox_wrap.checked {
  border-color: #1890ff;
  color: #1890ff;
}
.mock_checkbox_wrap.disabled {
  border-color: #e6ebf5;
  color: #c0c4cc;
  cursor: not-allowed;
}
.mock_checkbox {
  display: inline-block;
  box-sizing: border-box;
  width: 14px;
  height: 14px;
  border-radius: 2px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
}
.mock_checkbox_wrap.checked .mock_checkbox {
  position: relative;
  background-color: #1890ff;
  border-color: #1890ff;
}
.mock_checkbox_wrap.disabled .mock_checkbox {
  position: relative;
  background-color: #edf2fc;
  border-color: #dcdfe6;
}
.mock_checkbox_wrap.checked .mock_checkbox::after {
  box-sizing: content-box;
  position: absolute;
  content: "";
  width: 3px;
  height: 7px;
  left: 4px;
  top: 1px;
  border: 1px solid #fff;
  border-left: 0;
  border-top: 0;
  transition: transform .15s ease-in .05s;
  transform-origin: center;
  transform: rotate(45deg) scaleY(1);
}
</style>
